package gsw.common.login.loginFinger;

import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import gsw.tool.common.ToolShow;

/**
 * 指纹登录工具类
 * 需要添加权限：<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
 */
public class LoginFingerHelper {
    static LoginFingerHelper helper = null;
    //指纹登录管理器
    FingerprintManagerCompat fingerprintManager = null;
    FingerprintManagerCompat.CryptoObject mCryptoObject = null;
    CancellationSignal mCancellationSignal;
    FingerprintManagerCompat.AuthenticationCallback mAuthCallback;
    LoginFingerListener loginFingerListener;
    String keyName = "default_key";

    private LoginFingerHelper(Context context, LoginFingerListener listener) {
        this.loginFingerListener = listener;
        try {
            fingerprintManager = FingerprintManagerCompat.from(context);
            fingerprintManager.isHardwareDetected();

            mAuthCallback = new FingerprintManagerCompat.AuthenticationCallback() {
                @Override
                public void onAuthenticationError(int errMsgId, CharSequence errString) {
                    super.onAuthenticationError(errMsgId, errString);
                    if (loginFingerListener != null) {
                        loginFingerListener.onAuthenticationError(errMsgId, errString);
                    }
                }

                @Override
                public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                    super.onAuthenticationHelp(helpMsgId, helpString);
                    if (loginFingerListener != null) {
                        loginFingerListener.onAuthenticationHelp(helpMsgId, helpString);
                    }
                }

                @Override
                public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                    super.onAuthenticationSucceeded(result);
                    if (loginFingerListener != null) {
                        loginFingerListener.onAuthenticationSucceeded(result);
                    }
                }

                @Override
                public void onAuthenticationFailed() {
                    super.onAuthenticationFailed();
                    if (loginFingerListener != null) {
                        loginFingerListener.onAuthenticationFailed();
                    }
                }
            };

            Cipher defaultCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + KeyProperties.BLOCK_MODE_CBC + "/"
                    + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            if (initCipher(defaultCipher, keyName)) {
                mCryptoObject = new FingerprintManagerCompat.CryptoObject(defaultCipher);
            }
        } catch (Throwable e) {
            ToolShow.log(e.getMessage());
        }
    }

    public static LoginFingerHelper getInstance(Context context, LoginFingerListener loginFingerListener) {
        if (helper == null) {
            helper = new LoginFingerHelper(context, loginFingerListener);
        }
        if (helper.loginFingerListener != loginFingerListener) {
            helper.loginFingerListener = loginFingerListener;
        }
        return helper;
    }

    /**
     * 初始化cipher
     */
    private boolean initCipher(Cipher cipher, String keyName) {
        try {
            KeyStore mKeyStore = KeyStore.getInstance("AndroidKeyStore");
            mKeyStore.load(null);
            SecretKey key = (SecretKey) mKeyStore.getKey(keyName, null);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("Failed to init Cipher", e);
        }
    }

    /**
     * 检查手机是否支持指纹登录
     */
    public boolean isHardwareDetected() {
        return fingerprintManager.isHardwareDetected();
    }

    /**
     * 是否可用的指纹
     */
    public boolean hasEnrolledFingerprints() {
        return fingerprintManager.hasEnrolledFingerprints();
    }

    /**
     * 开启指纹监听
     */
    public void startListen() {
        if (isHardwareDetected() && hasEnrolledFingerprints()) {
            mCancellationSignal = new CancellationSignal();
            fingerprintManager.authenticate(mCryptoObject, 0, mCancellationSignal, mAuthCallback, null);
        }
    }

    /**
     * 关闭指纹监听
     */
    public void stopListen() {
        if (mCancellationSignal != null) {
            mCancellationSignal.cancel();
            mCancellationSignal = null;
        }
    }

}
